﻿using System;

using DataLayer.Repositories;
using DbEntities.Entities;
using EsbMonitor.Ninject;
using EsbMonitorMessages;
using NServiceBus;

namespace EsbMonitor.Handlers
{
    public class PublisherStartedEventHandler : IHandleMessages<IPublisherStartedEvent>
    {

        public IBus Bus { get; set; }

        #region IHandleMessages<IPublisherStartedEvent> Members

        public void Handle(IPublisherStartedEvent message)
        {

            var pubsRepo = KernelContainer.Get<IPublishersRepository>();

            Publisher publisher = pubsRepo.FindByInputQueueName(message.InputQueueName);

            if (publisher == null)
            {
                publisher = new Publisher
                                {
                                    FirstSeen = message.Time,
                                    InputQueueName =  message.InputQueueName,
                                    LastSeen = message.Time
                                };

                pubsRepo.Add(publisher);
            } else
            {
                publisher.LastSeen = message.Time;
                pubsRepo.Update(publisher);
            }

        }

        #endregion
    }
}